<script setup>
import { defineProps, ref, computed } from 'vue'
import axios from '../plugins/axios'
import { ElMessage } from 'element-plus'
import { config } from '../config'

const props = defineProps({
  lesson: {
    type: Object,
    required: true,
    default: () => ({
      title: '',
      publishTime: '',
      type: 1,
      content: '',
      attachment: '',
      attachmentName: '',
      user: {
        realname: '',
        head: ''
      }
    })
  }
})

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 默认头像URL
const defaultAvatar = '/default-avatar.png'

const downloading = ref(false)

const hasProtectedAttachment = computed(() => {
  const value = props.lesson?.attachment
  return !!value && !value.startsWith('http')
})

const downloadPermission = computed(() => {
  const allowed = props.lesson?.canDownloadAttachment !== false
  return {
    allowed,
    reason: allowed ? '' : (props.lesson?.downloadDenyReason || '暂无下载权限')
  }
})

const disableDownloadButton = computed(() => hasProtectedAttachment.value && !downloadPermission.value.allowed)

const handleDownload = async () => {
  if (!props.lesson?.attachment) return

  if (!hasProtectedAttachment.value) {
    window.open(props.lesson.attachment, '_blank')
    return
  }

  if (!downloadPermission.value.allowed) {
    ElMessage.warning(downloadPermission.value.reason || '当前账号暂无下载权限')
    return
  }

  try {
    downloading.value = true
    const response = await axios.post(`/lesson/${props.lesson.id}/download-token`, null, { suppressErrorToast: true })
    if (response.data.code === 1) {
      const { token } = response.data.data
      const url = `${config.baseURL}/lesson/download/${token}`
      window.open(url, '_blank')
    } else {
      ElMessage.error(response.data.msg || '获取下载令牌失败')
    }
  } catch (error) {
    console.error('下载失败', error)
    const message = error.response?.data?.msg || error.response?.data?.message || '下载失败，请稍后再试'
    ElMessage.error(message)
  } finally {
    downloading.value = false
  }
}
</script>

<template>
  <div class="lesson-detail">
    <h1 class="title">{{ lesson.title }}</h1>
    
    <div class="meta-info">
      <div class="info-item">
        <span class="label">发布时间:</span>
        <span class="value">{{ formatTime(lesson.publishTime) }}</span>
      </div>
      
      <div class="info-item author-info">
        <img 
          :src="lesson.user?.head || defaultAvatar" 
          :alt="lesson.user?.realname"
          class="author-avatar"
        />
        <span class="label">作者:</span>
        <span class="value">{{ lesson.user?.realname }}</span>
      </div>

      <div class="info-item">
        <span class="label">类型:</span>
        <span class="value">{{ lesson.type}}</span>
      </div>
    </div>
    
    <div class="content" v-html="lesson.content"></div>

    <!-- 附件下载区域 -->
    <div v-if="lesson.attachment" class="attachment-section">
      <h3>附件下载</h3>
      <div class="attachment-actions">
        <span class="file-name">{{ lesson.attachmentName || 'SOP 附件' }}</span>
        <el-button
          type="primary"
          size="small"
          :disabled="disableDownloadButton"
          :loading="downloading"
          @click="handleDownload"
          :title="disableDownloadButton ? downloadPermission.reason : ''"
        >
          下载附件
        </el-button>
      </div>
      <p v-if="disableDownloadButton" class="permission-hint">{{ downloadPermission.reason }}</p>
    </div>
  </div>
</template>

<style scoped>
.lesson-detail {
  max-width: 800px;
  margin: 2rem auto;
  padding: 2rem;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 1.8rem;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 1.5rem;
}

.meta-info {
  display: flex;
  justify-content: center;
  gap: 2rem;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid #eee;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.label {
  color: #666;
  font-size: 0.9rem;
}

.value {
  color: #333;
  font-weight: 500;
}

.content {
  line-height: 1.6;
  color: #444;
  font-size: 1.1rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 4px;
}

/* 富文本内容的样式 */
.content :deep(p) {
  margin-bottom: 1em;
}

.content :deep(img) {
  max-width: 100%;
  height: auto;
}

.content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 1em;
}

.content :deep(td), 
.content :deep(th) {
  border: 1px solid #ddd;
  padding: 8px;
}

.author-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 0.5rem;
}

.author-info {
  display: flex;
  align-items: center;
}

.attachment-section {
  margin-top: 2rem;
  padding-top: 1rem;
  border-top: 1px solid #eee;
}

.attachment-section h3 {
  color: #333;
  font-size: 1.2rem;
  margin-bottom: 1rem;
}

.attachment-section .el-link {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 1rem;
}

.permission-hint {
  margin-top: 0.5rem;
  color: #f56c6c;
  font-size: 0.9rem;
}

.attachment-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  padding: 12px 16px;
  background-color: #f5f7fa;
  border-radius: 6px;
}

.attachment-actions .file-name {
  color: #303133;
  font-weight: 500;
}
</style> 
